package com.hengyu.data.validator.factory;

import com.hengyu.data.validator.factory.validators.Validator;

import java.lang.annotation.Annotation;
import java.util.Hashtable;

/**
 * ========================
 * Created with IntelliJ IDEA.
 * User：恒宇少年
 * Date：2017/3/19
 * Time：16:36
 * 码云：http://git.oschina.net/jnyqy
 * ========================
 */
class HengYuValidationDynamicFactory {

    //key：注解名称,value：注解对应的validator实体对象
    static final Hashtable<String,Validator> _MEMORY_VALIDATORS = new Hashtable<String, Validator>();

    //validator所在package的前缀全路径
    static final String VALIDATOR_PREFFIX = "com.hengyu.data.validator.factory.validators";
    //validator的类名称后缀名
    static final String VALIDATOR_SUFFIX = "Validator";
    //禁止new对象
    private HengYuValidationDynamicFactory() {}

    /**
     * 根据注解名称动态反射出validator并且存放到内存
     * @param annotation
     * @return
     */
    public static Validator getValidator(Annotation annotation) throws Exception
    {
        //获取注解的类名（短类名）
        String annotationName = annotation.annotationType().getSimpleName();
        //先从内存中获取
        Validator validator = _MEMORY_VALIDATORS.get(annotationName);
        //如果内存中不存在，创建实例
        if(validator == null)
        {
            //根据validator名称规则创建validator对象
            Validator validator_instance = (Validator) Class.forName(VALIDATOR_PREFFIX + "." + annotationName + VALIDATOR_SUFFIX).newInstance();
            //给validator变量赋值为新创建validator对象
            validator = validator_instance;
            //将该validator对象存放到内存，下次直接从内存获取
            _MEMORY_VALIDATORS.put(annotationName,validator_instance);
        }
        //返回validator对象
        return validator;
    }
}
